package com.misc.tunewsreader;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TableLayout;
import android.widget.TextView;

import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.AbstractAction;

public class GroupView extends Activity {

	private List<NNTPGroup> groups;
	private SectionListAdapterCheck adapter;
	private GroupManager fav;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.groups);
		fav = new GroupManager(getApplicationContext());

		ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
		actionBar.setTitle(this.getString(R.string.all_groups));
		actionBar.addAction(new FilterAction(this, R.drawable.bar_search));
		actionBar.addAction(new DoneAction(this, R.drawable.bar_accept));

		loadGroups();
	}

	public static class DoneAction extends AbstractAction {
		private Context mContext;

		public DoneAction(Context context, int drawable) {
			super(drawable);
			mContext = context;
		}

		@Override
		public void performAction(View view) {
			((GroupView) mContext).setResult(0);
			((GroupView) mContext).finish();
		}
	}

	public static class FilterAction extends AbstractAction {
		private Context mContext;

		public FilterAction(Context context, int drawable) {
			super(drawable);
			mContext = context;
		}

		@Override
		public void performAction(View view) {
			TableLayout search_box_layout = (TableLayout) ((GroupView) mContext)
					.findViewById(R.id.search_box_layout);
			// toggle filter box
			if (search_box_layout.getVisibility() == View.GONE) {
				search_box_layout.setVisibility(View.VISIBLE);
				search_box_layout.requestFocus();
				InputMethodManager inputMethodManager = (InputMethodManager) mContext
						.getSystemService(Context.INPUT_METHOD_SERVICE);
				inputMethodManager.toggleSoftInputFromWindow(
						search_box_layout.getApplicationWindowToken(),
						InputMethodManager.SHOW_FORCED, 0);
			} else {
				search_box_layout.setVisibility(View.GONE);
				InputMethodManager inputMethodManager = (InputMethodManager) mContext
						.getSystemService(Context.INPUT_METHOD_SERVICE);
				inputMethodManager.toggleSoftInputFromWindow(
						search_box_layout.getApplicationWindowToken(),
						InputMethodManager.SHOW_FORCED, 0);
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_SEARCH:
			FilterAction action = new FilterAction(this, 0);
			action.performAction(null);
			return true;
		case KeyEvent.KEYCODE_BACK:
			setResult(0);
			finish();
			return true;
		}
		return false;
	}

	void loadGroups() {
		// display loading indicator
		((ActionBar) findViewById(R.id.actionbar))
				.setProgressBarVisibility(View.VISIBLE);

		Runnable viewGroup = new Runnable() {
			@Override
			public void run() {
				loadAllGroups();
				runOnUiThread(returnRes);
			}
		};
		Thread thread = new Thread(null, viewGroup, "LoadGroup");
		thread.start();
	}

	private Runnable returnRes = new Runnable() {
		@Override
		public void run() {
			displayAllGroups();

			// hide loading indicator
			((ActionBar) findViewById(R.id.actionbar))
					.setProgressBarVisibility(View.GONE);
		}
	};

	OnItemClickListener listener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			String s;
			CheckedTextView check = (CheckedTextView) view
					.findViewById(R.id.list_item_check_title);
			String group = ((TextView) view
					.findViewById(R.id.list_item_check_full_text)).getText()
					.toString();

			if (check.isChecked()) {
				// remove group
				fav.setFavorite(group, false);
				adapter.setChecked(position, false);
				adapter.notifyDataSetChanged();
				s = getApplicationContext().getString(R.string.remove) + " ";
				// delete all posts
				NNTPClient.resetGroup(NNTPGroup.fromName(group));
			} else {
				// add group
				fav.setFavorite(group, true);
				s = getApplicationContext().getString(R.string.add) + " ";
				adapter.setChecked(position, true);
				adapter.notifyDataSetChanged();
			}
			Log.d("NNTP", s);
		}

	};

	private void loadAllGroups() {
		groups = NNTPClient.getGroups();
		ArrayList<String> group = new ArrayList<String>();
		if (groups != null) {
			for (int i = 0; i < groups.size(); i++) {
				group.add(groups.get(i).getName());
			}
		}

		ArrayList<ListItem> items = fav.generateListView(group);

		adapter = new SectionListAdapterCheck(this, items);
	}

	private void displayAllGroups() {
		ListView group_list = (ListView) findViewById(R.id.group_groups);
		group_list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		group_list.setAdapter(adapter);
		group_list.setOnItemClickListener(listener);
		group_list.setTextFilterEnabled(true);

		EditText filter_text = (EditText) findViewById(R.id.search_box);
		filter_text.addTextChangedListener(filterTextWatcher);

		List<String> fav_groups = fav.getFavoriteList();

		// check favorite groups
		if (groups != null) {
			for (int i = 0; i < groups.size(); i++) {
				ListItem item = (ListItem) group_list.getItemAtPosition(i);
				if (item.isSection())
					continue;

				if (fav_groups.contains(((ListEntry) item).full_name)) {
					adapter.setChecked(i, true);
				} else {
					adapter.setChecked(i, false);
				}
			}
		}

	}

	private TextWatcher filterTextWatcher = new TextWatcher() {

		public void afterTextChanged(Editable text) {
		}

		public void beforeTextChanged(CharSequence text, int start, int count,
				int after) {
		}

		public void onTextChanged(CharSequence text, int start, int before,
				int count) {
			adapter.getFilter().filter(text);
		}

	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// loadAllGroups();

		super.onActivityResult(requestCode, resultCode, data);
	}

}
